import axios from 'axios';
import apiConfig from '../config/api';

class ApiService {
  constructor() {
    this.api = axios.create({
      baseURL: "",
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 添加请求拦截器
    this.api.interceptors.request.use(
      (config) => {
        // 在发送请求之前做些什么
        const token = localStorage.getItem('token');
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
      }
    );

    // 添加响应拦截器
    this.api.interceptors.response.use(
      (response) => {
        // 对响应数据做点什么
        console.log('API响应:', response);
        // 返回response.data，符合Vue Axios响应处理规范
        return response;
      },
      (error) => {
        // 对响应错误做点什么
        console.error('API错误:', error);
        if (error.response && error.response.status === 401) {
          // 处理未授权错误
          localStorage.removeItem('token');
          window.location.href = '/stockui/login';
        }
        return Promise.reject(error);
      }
    );
  }

  // 股票代码验证函数
  validateStockSymbol(symbol) {
    // 检查是否为空
    if (!symbol) {
      return {
        isValid: false,
        error: '股票代码不能为空'
      };
    }

    // 检查是否为字符串
    if (typeof symbol !== 'string') {
      return {
        isValid: false,
        error: '股票代码必须是字符串'
      };
    }

    // 去除空格
    symbol = symbol.trim();

    // 检查是否为6位数字
    if (!/^\d{6}$/.test(symbol)) {
      return {
        isValid: false,
        error: '股票代码必须是6位数字'
      };
    }

    // 检查是否为有效的A股代码
    const validPrefixes = ['000', '002', '300', '600', '601', '603', '688'];
    const prefix = symbol.substring(0, 3);
    
    if (!validPrefixes.includes(prefix)) {
      return {
        isValid: false,
        error: '无效的股票代码前缀。有效的前缀包括：000, 002, 300 (深圳), 600, 601, 603, 688 (上海)'
      };
    }

    return {
      isValid: true,
      error: null
    };
  }

  // Auth API
  async register(userData) {
    console.log('注册请求:', userData);
    try {
      const response = await this.api.post(apiConfig.AUTH.REGISTER, userData);
      console.log('注册响应:', response);
      return response.data;
    } catch (error) {
      console.error('注册错误:', error);
      throw error;
    }
  }

  async login(credentials) {
    console.log('登录请求:', credentials);
    try {
      const response = await this.api.post(apiConfig.AUTH.LOGIN, credentials);
      console.log('登录响应:', response);
      return response.data;
    } catch (error) {
      console.error('登录错误:', error);
      throw error;
    }
  }

  // 验证JWT token
  verifyToken(token) {
    try {
      // 简单的JWT解析（只解析payload部分，不验证签名）
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      }).join(''));
      
      const payload = JSON.parse(jsonPayload);
      return {
        success: true,
        userId: payload.userId,
        username: payload.username
      };
    } catch (error) {
      return {
        success: false,
        message: 'Invalid token'
      };
    }
  }

  // Stocks API
  async getAllStocks() {
    try {
      const response = await this.api.get(apiConfig.STOCKS.GET_ALL);
      return response;
    } catch (error) {
      console.error('获取股票列表错误:', error);
      throw error;
    }
  }

  // 获取所有股票信息
  async getAllStockInfo() {
    try {
      const response = await this.api.get(`${apiConfig.STOCKS.GET_ALL}/info`);
      return response.data;
    } catch (error) {
      console.error('获取股票信息错误:', error);
      throw error;
    }
  }

  // 根据市场类型获取股票信息
  async getStocksByMarket(market) {
    try {
      const response = await this.api.get(`${apiConfig.STOCKS.GET_ALL}/info/${market}`);
      return response.data;
    } catch (error) {
      console.error('获取股票信息错误:', error);
      throw error;
    }
  }

  // 搜索股票信息
  async searchStocks(keyword) {
    try {
      const response = await this.api.get(`${apiConfig.STOCKS.GET_ALL}/info/search/${keyword}`);
      return response.data;
    } catch (error) {
      console.error('搜索股票信息错误:', error);
      throw error;
    }
  }

  async getStockBySymbol(symbol) {
    // 验证股票代码
    const validation = this.validateStockSymbol(symbol);
    if (!validation.isValid) {
      throw new Error(validation.error);
    }
    
    try {
      const response = await this.api.get(apiConfig.STOCKS.GET_BY_SYMBOL(symbol));
      return response.data;
    } catch (error) {
      console.error('获取股票详情错误:', error);
      throw error;
    }
  }

  async getRealStockData(symbol) {
    // 验证股票代码
    const validation = this.validateStockSymbol(symbol);
    if (!validation.isValid) {
      throw new Error(validation.error);
    }
    
    try {
      const response = await this.api.get(apiConfig.STOCKS.GET_REAL(symbol));
      return response.data;
    } catch (error) {
      console.error('获取实时股票数据错误:', error);
      throw error;
    }
  }

  async getMultipleRealStockData(symbols) {
    // 验证所有股票代码
    for (const symbol of symbols) {
      const validation = this.validateStockSymbol(symbol);
      if (!validation.isValid) {
        throw new Error(`股票代码 ${symbol} 无效: ${validation.error}`);
      }
    }
    
    try {
      const response = await this.api.post(apiConfig.STOCKS.GET_REAL_MULTIPLE, { symbols });
      return response.data;
    } catch (error) {
      console.error('获取多个实时股票数据错误:', error);
      throw error;
    }
  }

  async updateStockPrice(symbol, price) {
    // 验证股票代码
    const validation = this.validateStockSymbol(symbol);
    if (!validation.isValid) {
      throw new Error(validation.error);
    }
    
    try {
      const response = await this.api.put(apiConfig.STOCKS.UPDATE_PRICE(symbol), { price });
      return response.data;
    } catch (error) {
      console.error('更新股票价格错误:', error);
      throw error;
    }
  }

  async simulatePriceChanges() {
    try {
      const response = await this.api.post(apiConfig.STOCKS.SIMULATE);
      return response.data;
    } catch (error) {
      console.error('模拟价格变动错误:', error);
      throw error;
    }
  }

  // Trades API
  async createTrade(tradeData) {
    try {
      const response = await this.api.post(apiConfig.TRADES.CREATE, tradeData);
      return response.data;
    } catch (error) {
      console.error('创建交易错误:', error);
      throw error;
    }
  }

  async executeTrade(tradeId) {
    try {
      const response = await this.api.post(apiConfig.TRADES.EXECUTE(tradeId));
      return response.data;
    } catch (error) {
      console.error('执行交易错误:', error);
      throw error;
    }
  }

  async cancelTrade(tradeId) {
    try {
      const response = await this.api.post(apiConfig.TRADES.CANCEL(tradeId));
      return response.data;
    } catch (error) {
      console.error('取消交易错误:', error);
      throw error;
    }
  }

  async getTradeById(tradeId) {
    try {
      const response = await this.api.get(apiConfig.TRADES.GET_BY_ID(tradeId));
      return response.data;
    } catch (error) {
      console.error('获取交易详情错误:', error);
      throw error;
    }
  }

  async getAllTrades() {
    try {
      const response = await this.api.get(apiConfig.TRADES.GET_ALL);
      return response.data;
    } catch (error) {
      console.error('获取所有交易错误:', error);
      throw error;
    }
  }

  async getTradesBySymbol(symbol) {
    try {
      const response = await this.api.get(apiConfig.TRADES.GET_BY_SYMBOL(symbol));
      return response.data;
    } catch (error) {
      console.error('根据股票代码获取交易错误:', error);
      throw error;
    }
  }

  // Users API
  async createUser(userData) {
    try {
      const response = await this.api.post(apiConfig.USERS.CREATE, userData);
      return response.data;
    } catch (error) {
      console.error('创建用户错误:', error);
      throw error;
    }
  }

  async getUserById(userId) {
    try {
      const response = await this.api.get(apiConfig.USERS.GET_BY_ID(userId));
      return response.data;
    } catch (error) {
      console.error('获取用户详情错误:', error);
      throw error;
    }
  }

  async getAllUsers() {
    try {
      const response = await this.api.get(apiConfig.USERS.GET_ALL);
      return response.data;
    } catch (error) {
      console.error('获取所有用户错误:', error);
      throw error;
    }
  }

  async buyStock(userId, tradeData) {
    try {
      const response = await this.api.post(apiConfig.USERS.BUY_STOCK(userId), tradeData);
      return response.data;
    } catch (error) {
      console.error('买入股票错误:', error);
      throw error;
    }
  }

  async sellStock(userId, tradeData) {
    try {
      const response = await this.api.post(apiConfig.USERS.SELL_STOCK(userId), tradeData);
      return response.data;
    } catch (error) {
      console.error('卖出股票错误:', error);
      throw error;
    }
  }

  async getUserPortfolio(userId) {
    try {
      const response = await this.api.get(apiConfig.USERS.GET_PORTFOLIO(userId));
      return response.data;
    } catch (error) {
      console.error('获取用户投资组合错误:', error);
      throw error;
    }
  }

  // Strategies API
  async createStrategy(strategyData) {
    try {
      const response = await this.api.post(apiConfig.STRATEGIES.CREATE, strategyData);
      return response.data;
    } catch (error) {
      console.error('创建策略错误:', error);
      throw error;
    }
  }

  async getStrategies() {
    try {
      const response = await this.api.get(apiConfig.STRATEGIES.GET_ALL);
      return response.data;
    } catch (error) {
      console.error('获取所有策略错误:', error);
      throw error;
    }
  }

  async getStrategyById(id) {
    try {
      const response = await this.api.get(apiConfig.STRATEGIES.GET_BY_ID(id));
      return response.data;
    } catch (error) {
      console.error('获取策略详情错误:', error);
      throw error;
    }
  }

  async updateStrategy(id, strategyData) {
    try {
      const response = await this.api.put(apiConfig.STRATEGIES.UPDATE(id), strategyData);
      return response.data;
    } catch (error) {
      console.error('更新策略错误:', error);
      throw error;
    }
  }

  async deleteStrategy(id) {
    try {
      const response = await this.api.delete(apiConfig.STRATEGIES.DELETE(id));
      return response.data;
    } catch (error) {
      console.error('删除策略错误:', error);
      throw error;
    }
  }

  async executeMovingAverageStrategy(strategyData) {
    try {
      const response = await this.api.post(apiConfig.STRATEGIES.EXECUTE_MA, strategyData);
      return response.data;
    } catch (error) {
      console.error('执行移动平均线策略错误:', error);
      throw error;
    }
  }

  async executeRSIStrategy(strategyData) {
    try {
      const response = await this.api.post(apiConfig.STRATEGIES.EXECUTE_RSI, strategyData);
      return response.data;
    } catch (error) {
      console.error('执行RSI策略错误:', error);
      throw error;
    }
  }

  async executeBollingerBandsStrategy(strategyData) {
    try {
      const response = await this.api.post(apiConfig.STRATEGIES.EXECUTE_BB, strategyData);
      return response.data;
    } catch (error) {
      console.error('执行布林带策略错误:', error);
      throw error;
    }
  }

  async executeTurtleTradingStrategy(strategyData) {
    try {
      const response = await this.api.post(apiConfig.STRATEGIES.EXECUTE_TURTLE, strategyData);
      return response.data;
    } catch (error) {
      console.error('执行海龟交易策略错误:', error);
      throw error;
    }
  }

  // 添加多因子策略执行方法
  async executeMultiFactorStrategy(strategyData) {
    try {
      const response = await this.api.post(apiConfig.STRATEGIES.EXECUTE_MULTI_FACTOR, strategyData);
      return response.data;
    } catch (error) {
      console.error('执行多因子策略错误:', error);
      throw error;
    }
  }

  // Stock History API
  async getStockHistory(symbol, limit = 100) {
    try {
      const response = await this.api.get(`${apiConfig.STOCKS.GET_BY_SYMBOL(symbol)}/history`, {
        params: { limit }
      });
      return response.data;
    } catch (error) {
      console.error('获取股票历史数据错误:', error);
      throw error;
    }
  }

  async updateStockHistory(symbol) {
    try {
      const response = await this.api.post(`${apiConfig.STOCKS.GET_BY_SYMBOL(symbol)}/history/update`);
      return response.data;
    } catch (error) {
      console.error('更新股票历史数据错误:', error);
      throw error;
    }
  }
}

export default new ApiService();